package com.iwhalecloud.bss.kite.cucc.order.util;

import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.KiteAttrConfigCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteAttrConfig;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItemRel;
import com.iwhalecloud.bss.kite.dataservice.util.IdUtils;
import com.iwhalecloud.bss.kite.order.client.context.OrderContext;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.base.staticdata.CoreDataInteract;
import com.ztesoft.bss.order.base.consts.BTables.ORDER_ITEM;
import com.ztesoft.bss.order.base.consts.KeyValues;
import com.ztesoft.bss.order.base.consts.KeyValuesLocal;
import com.ztesoft.bss.order.base.orm.conf.BusiConfigTables;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
 * <Description> <br>
 * 订单项关系关联处理辅助工具类
 *
 * @author wjy<br>
 * @version 1.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.order.util <br>
 * @since R9.0<br>
 */
public abstract class OrderRelUtil {

    /**
     * 订单衍生关系1600, 非衍生关系1700
     */
    public static void setDeriveOderRel(OrderRequest request) {
        List<OrderItem> orderItemInfos = new ArrayList<OrderItem>();
        Map<String, OrderItem> orderItemMap = request.getOrderContainer().getOrderItemMap();
        for (OrderItem orderItems : orderItemMap.values()) {
            orderItemInfos.add(orderItems);
        }

        //预存款充值不处理
        String serviceOfferId = OrderContext.getOrderRequest().getServiceOfferId();

        if (KeyValuesLocal.SERVICE_OFFER_YCKCZ.equals(serviceOfferId)) {
            return;
        }

        //没有订单或只有一张订单时没有衍生关系
        if (KiteListUtils.isEmpty(orderItemInfos) || orderItemInfos.size() == 1) {
            return;
        }

        //订单按ask_id分组
        Map<String, List<OrderItem>> group = getGroup(orderItemInfos);
        if (group == null || group.isEmpty()) {
            return;
        }
        dealRel(group);

    }

    public static void dealRel(Map<String, List<OrderItem>> group) {
        String serviceOfferId = OrderContext.getOrderRequest().getServiceOfferId();
        Iterator<Entry<String, List<OrderItem>>> itr = group.entrySet().iterator();
        while (itr.hasNext()) {
            Entry<String, List<OrderItem>> entry = itr.next();
            String askId = entry.getKey();
            List<OrderItem> orderItemList = entry.getValue();
            OrderItem aOrderItem = getAOrderItem(orderItemList, askId, serviceOfferId);
            if (aOrderItem == null) {
                continue;
            }

            String aOrderItemId = aOrderItem.getOrderItemId();
            String aServiceOfferId = aOrderItem.getServiceOfferId();
            String aProdOfferId = aOrderItem.getApplyObjSpec();
            String createStaff = aOrderItem.getCreateStaff();

            for (OrderItem zOrderItem : orderItemList) {
                String zOrderItemId = zOrderItem.getOrderItemId();
                String zServiceOfferId = zOrderItem.getServiceOfferId();
                String zProdOfferId = zOrderItem.getApplyObjSpec();
                String zCustId = zOrderItem.getBelongCustId();

                //主单和衍生的order_item_id不能相同
                if (aOrderItemId.equals(zOrderItemId)) {
                    continue;
                }

                //如果是订购业务
                if (KeyValuesLocal.SERVICE_OFFER_INSTALL.equals(serviceOfferId)) {
                    //判断销售品实例是否从选购台生成的，从选购台生成的销售品实例订购单不算衍生单，其他的订购单都算衍生单
                    if (KeyValuesLocal.SERVICE_OFFER_INSTALL.equals(zServiceOfferId)) {

                        saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, false, zCustId);
                    }
                    //不是订购业务的都算衍生单
                    else {
                        saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, true, zCustId);
                    }
                }
                //如果不是订购业务
                else {
                    //是否已经从配置中处理
                    boolean isContinue = true;

                    //特殊情况先按照配置的业务判断是否衍生单(dc_public.stype = 666)
                    List<DcPublic> configList = getConfig(aServiceOfferId);
                    if (!KiteListUtils.isEmpty(configList)) {
                        for (DcPublic config : configList) {
                            //衍生单的业务ID
                            String pcode = config.getPcode();
                            if (zServiceOfferId.equals(pcode)) {
                                //0表示不是衍生单，1表示是衍生单
                                String codea = config.getCodea();
                                //当前的销售品ID
                                String codeb = config.getCodeb();
                                //关联的销售品ID
                                String codec = config.getCodec();

                                if (StringUtils.isNotBlank(codeb)) {
                                    //如果配置了当前销售品ID，需要判断当前销售品ID是否匹配
                                    if (codeb.indexOf(aProdOfferId) != -1) {
                                        if (StringUtils.isNotBlank(codec) && codec.indexOf(zProdOfferId) != -1) {

                                            isTypeYet(codea, aOrderItemId, zOrderItemId, createStaff, zCustId);
                                            isContinue = false;
                                            break;

                                        }
                                        else {

                                            isTypeYet(codea, aOrderItemId, zOrderItemId, createStaff, zCustId);
                                            isContinue = false;
                                            break;
                                        }
                                    }
                                }
                                else {
                                    if (StringUtils.isNotBlank(codec)) {
                                        if (codec.indexOf(zProdOfferId) != -1) {
                                            isTypeYet(codea, aOrderItemId, zOrderItemId, createStaff, zCustId);
                                            isContinue = false;
                                            break;
                                        }
                                    }
                                    else {
                                        isTypeYet(codea, aOrderItemId, zOrderItemId, createStaff, zCustId);
                                        isContinue = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    //没有配置的按通用情况判断
                    if (isContinue) {
                        //如果是订购单，并且是从选购台订购的，不算衍生单
                        if (KeyValuesLocal.SERVICE_OFFER_INSTALL.equals(zServiceOfferId)) {
                            saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, false, zCustId);
                        }
                        //和当前业务不相同的订单都算衍生单
                        else if (!aServiceOfferId.equals(zServiceOfferId)) {
                            saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, true, zCustId);
                        }
                        else {
                            saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, false, zCustId);
                        }
                    }
                }
            }
        }
    }

    private static void isTypeYet(String codea, String aOrderItemId, String zOrderItemId, String createStaff, String zCustId) {
        if ("1".equals(codea)) {
            saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, true, zCustId);
        }
        else {
            saveOrderItemRel(aOrderItemId, zOrderItemId, createStaff, false, zCustId);
        }

    }

    /**
     * 按照ask_id对订单进行分组
     */
    private static Map<String, List<OrderItem>> getGroup(List<OrderItem> orderItems) {
        Map<String, List<OrderItem>> group = new HashMap<String, List<OrderItem>>();
        if (KiteListUtils.isEmpty(orderItems)) {
            return group;
        }

        for (OrderItem orderItem : orderItems) {
            String askId = orderItem.getAskId();
            if (group.containsKey(askId)) {
                group.get(askId).add(orderItem);
            }
            else {
                List<OrderItem> orderItemList = new ArrayList<OrderItem>();
                orderItemList.add(orderItem);
                group.put(askId, orderItemList);
            }
        }

        return group;
    }

    /**
     * 保存衍生单关系
     */
    public static void saveOrderItemRel(String aOrderItemId, String zOrderItemId, String createStaff, boolean yes, String custId) {
        if (org.apache.commons.lang.StringUtils.isBlank(aOrderItemId) || org.apache.commons.lang.StringUtils.isBlank(zOrderItemId)) {
            return;
        }

        // 判断是否已经存在z端的单
        Map<String, OrderItemRel> orderItemRelMap = OrderContext.getOrderRequest().getOrderContainer().getOrderItemRelMap();
        Map<String, String> orderItemRelMap1 = isExtOrderItemRel(orderItemRelMap, zOrderItemId, custId);
        // 已经存在衍生单或非衍生单关系，不重复保存
        if (orderItemRelMap1 != null && !orderItemRelMap1.isEmpty()) {
            return;
        }
        // 订单项关系类型由2.0的KeyValuesLocal.ORDER_ITEM_REL_101（衍生单关系）改为3.0的CoreDataInteract.EVT_C_0004_1600(衍生单关系) modify by
        // 订单项关系类型由2.0的KeyValuesLocal.ORDER_ITEM_REL_102（非衍生单关系）改为3.0的CoreDataInteract.EVT_C_0004_1700(非衍生单关系) modify by
        String order_rel_type = yes ? CoreDataInteract.EVT_C_0004_1600 : CoreDataInteract.EVT_C_0004_1700;
        OrderItemRel orderItemRel = new OrderItemRel();
        String seqProductOrderRelId = IdUtils.getSeqProductOrderRelId();
        orderItemRel.setOrderItemRelId(seqProductOrderRelId);
        orderItemRel.setOrderItemId(aOrderItemId);
        orderItemRel.setZOrderItemId(zOrderItemId);
        orderItemRel.setRelType(order_rel_type);
        orderItemRel.setCreateStaff(createStaff);
        orderItemRel.setCustId(custId);
        // 【BSS3.0入网检测】增加订单关联关系状态
        orderItemRel.setStatusCd(CoreDataInteract.EVT_0001_101300);

        orderItemRelMap.put(seqProductOrderRelId, orderItemRel);
    }

    private static Map<String, String> isExtOrderItemRel(Map<String, OrderItemRel> orderItemRelMap, String zOrderItemId, String custId) {
        Map<String, String> map = new HashMap<>();
        for (OrderItemRel rel : orderItemRelMap.values()) {
            String zOrderItemIdExt = rel.getZOrderItemId();
            String custIdExt = rel.getCustId();
            if (zOrderItemId.equals(zOrderItemIdExt) && custIdExt.equals(custId)) {
                map = KiteMapUtils.beanToMap(rel);
            }
        }
        return map;
    }

    /**
     * 获取判断是否衍生单的配置
     */
    private static List<DcPublic> getConfig(String pkey) {
        if (StringUtils.isBlank(pkey)) {
            return null;
        }
        List<DcPublic> byPkey = DcPublicCache.getByPkey(KeyValues.STYPE_666, pkey);
        return byPkey;
    }


    /**
     * 取出一组订单中的主单
     */
    private static OrderItem getAOrderItem(List<OrderItem> orderItemList, String askId, String serviceOfferId) {
        if (KiteListUtils.isEmpty(orderItemList) || StringUtils.isBlank(askId) || StringUtils.isBlank(serviceOfferId)) {
            return null;
        }

        //首先找订单ID和ask_id相同，并且订单的业务和当前业务相同的订单
        for (OrderItem orderItem : orderItemList) {
            String oServiceOfferId = orderItem.getServiceOfferId();
            if (askId.equals(orderItem.getOrderItemId()) && serviceOfferId.equals(oServiceOfferId)) {
                return orderItem;
            }
        }

        //尽量让主单的业务和当前业务相同，目前发现ask_id不一定是当前业务的主订单ID
        for (OrderItem orderItem : orderItemList) {
            String oServiceOfferId = orderItem.getServiceOfferId();
            if (serviceOfferId.equals(oServiceOfferId)) {
                return orderItem;
            }
        }

        //销售品修改特殊处理，找订购的订单做为主单
        if (KeyValuesLocal.XIUGAI_SERVICE.equals(serviceOfferId)) {
            for (OrderItem orderItem : orderItemList) {
                String oServiceOfferId = orderItem.getServiceOfferId();
                if (KeyValuesLocal.SERVICE_OFFER_INSTALL.equals(oServiceOfferId)) {
                    return orderItem;
                }
            }
        }

        return null;
    }


    public static KiteAttrConfig isExistTable(String fieldName, String serviceOfferId, String table) {
        List<KiteAttrConfig> kiteAttrConfig = KiteAttrConfigCache.getAttrConfigTable(fieldName, serviceOfferId);
        for (KiteAttrConfig attrConfig : kiteAttrConfig) {
            String tableName = attrConfig.getTableName();
            if (table.equals(tableName)) {
                return attrConfig;
            }
        }
        return null;
    }

    /**
     * 设置同笔竣工标识
     * @param orderRequest
     */
    public static void setSameFinishAgreementId(OrderRequest orderRequest) {
        OrderRequest request = OrderContext.getOrderRequest();
        if (ServiceOfferConsts.TRANSFER_PROD_INST.equals(request.getServiceOfferId())) {
            return;
        }
        List<OrderItem> orderItems = OrderContainer.ofRequest(orderRequest).listOrderItems();
        String agreementId = SeqUtils.getNext(BusiConfigTables.ORDER_ITEM.name(), ORDER_ITEM.agreement_id);
        for (OrderItem item :orderItems) {
            item.setAgreementId(agreementId);
            OrderContainer.ofRequest(orderRequest).addOrderItem(item);
        }

    }
}

